package com.spider.site.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.spider.site.dao.base.BaseDao;
import com.spider.site.dao.SpiderResultDao;
import com.spider.site.entity.SpiderResult;

@Repository
public class SpiderResultDaoImpl extends BaseDao<SpiderResult> implements SpiderResultDao{

	@Override
	public List<SpiderResult> getAll() {
		return super.getAll(new SpiderResult());
	}

	@Override
	public boolean saveSpiderResult(SpiderResult reslut) {
		return super.save(reslut);
	}

	@SuppressWarnings("unchecked")
	@Override
	public SpiderResult getSpiderResultByURL(String url) {
		final String hql = " FROM SpiderResult WHERE url = :url ";
		List<SpiderResult> resultList = super.entityManager.createQuery(hql)
				.setParameter("url", url).getResultList();
		if(resultList.size() > 0)
			return resultList.get(0);
		return null; 
	}

	@Override
	public boolean editSpiderResult(SpiderResult spider) {
		return super.update(spider);
	}

	@Override
	public boolean removeSpiderResult(long id) {
		SpiderResult spiderResult = this.getSpiderResultById(id);
		if(spiderResult != null) {
			return super.delete(spiderResult);
		}
		return false;
	}

	@Override
	public SpiderResult getSpiderResultById(long id) {
		return super.get(id, new SpiderResult());
	}

	@Override
	public int editSpiderSpin(int spin , long id) {
		String hql = " UPDATE SpiderResult SET isSpin = :spin WHERE id = :id ";
		if(spin == 0) {
			hql = " UPDATE SpiderResult SET isSpin = :spin , isSpinging = 0 WHERE id = :id ";
		}
		return super.entityManager.createQuery(hql)
				.setParameter("spin", spin).setParameter("id", id)
				.executeUpdate();
	}

}
